package kr.or.common.security.ibatis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import kr.or.common.security.ibatis.domain.CustomGrantedAuthority;
import kr.or.common.security.ibatis.domain.*;
import kr.or.javacafe.member.domain.*;
import kr.or.javacafe.member.bo.*;


@Transactional
public class IbatisUserDetailManager implements UserDetailsService {

	@Autowired
	private MemberBO memberBO;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
				
		User param = new User();
		param.setId(username);
		
		List<GrantedAuthority> gAuthList = new ArrayList<GrantedAuthority> ();
		User user = memberBO.getUser(param);
		if (user != null) {
			if (user.getRoleAuthList() != null) {
				for (RoleAuth role : user.getRoleAuthList()) {
					CustomGrantedAuthority gAuth = new CustomGrantedAuthority(role.getRoleAuth());
					gAuthList.add(gAuth);
				}				
			} else {
				CustomGrantedAuthority gAuth = new CustomGrantedAuthority("ROLE_USER");
				gAuthList.add(gAuth);				
			}
		} else {
			throw new UsernameNotFoundException(username + " not found user!!!!");
		}
		
		IbatisUserDetail userDetail = new IbatisUserDetail(user, gAuthList);
		
		return userDetail;
	}
	
}
